//
//  DQRSXViewController.m
//  uplife
//
//  Created by ZhangCheng on 2018/12/27.
//  Copyright © 2018年 ZhangCheng. All rights reserved.
//

#import "DQRSXViewController.h"
#import "DQRSXDetailTableViewController.h"
@interface DQRSXViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property(nonatomic,strong)IBOutlet UIBarButtonItem *editBtn;
@property(nonatomic,strong)IBOutlet UIBarButtonItem *quanXuanBtn;
@property(nonatomic,strong)IBOutlet UIBarButtonItem *cancelBtn;

@property(nonatomic,weak)IBOutlet UIView *toolView;
@property(nonatomic,weak)IBOutlet UIView *searchBarSuperView;
@property(nonatomic,weak)IBOutlet UITextField *searchTF;

@property(nonatomic,weak)IBOutlet UITableView *tableView;

@property(nonatomic,strong)NSArray *dataArray;
@property(nonatomic,strong)NSArray *dataWithDateArray;
@end

@implementation DQRSXViewController

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self sendRequestForLoadData];
    [textField resignFirstResponder];
    return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.toolView.layer.shadowColor = [UIColor colorWithRed:113/255.0 green:72/255.0 blue:11/255.0 alpha:0.3].CGColor;
    self.toolView.layer.shadowOffset = CGSizeMake(0,0);
    self.toolView.layer.shadowOpacity = 1;
    self.toolView.layer.shadowRadius = 10;
    [self.searchBarSuperView.layer setBorderColor:[UIColor colorWithRed:203/255.0 green:172/255.0 blue:116/255.0 alpha:1.0].CGColor];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self sendRequestForLoadData];
}

-(void)sendRequestForLoadData{
    NSString *keyWords = [self.searchTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    
    NSString *urlString = [NSString stringWithFormat:@"%@/message/list.do",JSXF_HOST];
    NSDictionary *param = @{};
    if (keyWords.length!=0) {
//        urlString = [NSString stringWithFormat:@"%@/message/list.do?keywords=%@",JSXF_HOST,keyWords];
        param = @{@"keywords":keyWords};
    }
    [SVProgressHUD show];
    
    [ZCWebServiceHelper requestWithMethod:POST andUrlStr:urlString andParameters:param andFinished:^(id response, NSURLSessionDataTask *dataTask) {
        [SVProgressHUD dismiss];
        if (![response[@"data"] isKindOfClass:[NSString class]]) {
            NSDictionary *dic = response;
            self.dataArray = dic[@"data"][@"dataList"];
            [self dealData];
            [self.tableView reloadData];
        }
        
    }];
}

-(void)dealData{
    NSMutableArray *mArray = [[NSMutableArray alloc]init];
    for (NSDictionary *dic in self.dataArray) {
        NSString *sendTime = dic[@"sendTime"];
        NSString *sendTimeFirstPart = [sendTime componentsSeparatedByString:@" "].firstObject;
        NSMutableDictionary *lastDic = mArray.lastObject;
        if (lastDic==nil) {
            lastDic = [[NSMutableDictionary alloc]init];
            [lastDic setObject:sendTimeFirstPart forKey:@"date"];
            [lastDic setObject:[[NSMutableArray alloc]init] forKey:@"data"];
            [mArray addObject:lastDic];
        }
        NSMutableArray *dataArray = lastDic[@"data"];
        NSString *dateString = lastDic[@"date"];
        if (![dateString isEqualToString:sendTimeFirstPart]) {
            dataArray = [[NSMutableArray alloc]init];
            lastDic = [[NSMutableDictionary alloc]init];
            [lastDic setObject:sendTimeFirstPart forKey:@"date"];
            [lastDic setObject:dataArray forKey:@"data"];
            [mArray addObject:lastDic];
        }
        [dataArray addObject:dic];
    }
    self.dataWithDateArray = [NSArray arrayWithArray:mArray];
}

-(IBAction)editAction{
    self.navigationItem.leftBarButtonItem = self.cancelBtn;
    self.navigationItem.rightBarButtonItem = self.quanXuanBtn;
    self.toolView.hidden = NO;
    [self.tableView setEditing:YES animated:YES];
}

-(IBAction)cancelAction{
    self.navigationItem.backBarButtonItem.enabled = YES;
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.rightBarButtonItem = self.editBtn;
    self.toolView.hidden = YES;
    [self.tableView setEditing:NO animated:YES];
}

-(IBAction)selectAllAction{
    for (NSInteger m = 0; m<self.dataWithDateArray.count; m++) {
        NSDictionary *dic = self.dataWithDateArray[m];
        NSArray *dataArray = dic[@"data"];
        for (NSInteger n=0; n<dataArray.count; n++) {
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:n inSection:m] animated:NO scrollPosition:UITableViewScrollPositionTop];
        }
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataWithDateArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSDictionary *dic = self.dataWithDateArray[section];
    NSArray *dataArray = dic[@"data"];
    return dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectedBackgroundView = [UIView new];
    cell.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:246/255.0 green:231/255.0 blue:206/255.0 alpha:1.0];
//    cell.multipleSelectionBackgroundView = [UIView new];
//    cell.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:246/255.0 green:231/255.0 blue:206/255.0 alpha:1.0];
    
    NSDictionary *dicSection = self.dataWithDateArray[indexPath.section];
    NSArray *dataArray = dicSection[@"data"];
    NSDictionary *dic = dataArray[indexPath.row];
    
    UILabel *titleLabel = [cell viewWithTag:1];
    UILabel *contentLabel = [cell viewWithTag:2];
    UIView *isReadView = [cell viewWithTag:3];
    UIImageView *importanceImageView = [cell viewWithTag:4];
    UIImageView *lockImageView = [cell viewWithTag:5];
    UIImageView *confirmImageView = [cell viewWithTag:6];

    titleLabel.text = [NSString stringWithFormat:@"%@",dic[@"title"]];
    contentLabel.text = [NSString stringWithFormat:@"%@",dic[@"content"]];
    isReadView.hidden =  ((NSNumber*)dic[@"isRead"]).integerValue!=0;
    importanceImageView.hidden =  ((NSNumber*)dic[@"isImportance"]).integerValue==0;
    lockImageView.hidden =  ((NSNumber*)dic[@"isLock"]).integerValue==0;
    confirmImageView.hidden =  ((NSNumber*)dic[@"isSure"]).integerValue!=1;

    
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
        UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
        if (!headerView) {
            headerView = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"headerView"];
            [headerView setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 35.0f)];
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15.0f, 10.0f, 75.0f, 21.0f)];
            label.layer.cornerRadius = 10.5f;
            label.layer.masksToBounds = YES;
            label.backgroundColor = [UIColor colorWithRed:203/255.0 green:172/255.0 blue:116/255.0 alpha:1.0];
            label.textAlignment = NSTextAlignmentCenter;
            label.tag = 1;
            
            
            
            [label setFont:[UIFont fontWithName:@"HiraginoSans-W3" size: 10]];
            [label setTextColor: [UIColor colorWithRed:28/255.0 green:32/255.0 blue:41/255.0 alpha:1.0]];
            [headerView.contentView addSubview:label];
            
            [headerView.contentView setBackgroundColor:self.view.backgroundColor];
        }
    NSDictionary *dic = self.dataWithDateArray[section];
    UILabel *titleLabel = [headerView viewWithTag:1];
    [titleLabel setText:dic[@"date"]];

    return headerView;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.isEditing==NO) {
        NSDictionary *dicSection = self.dataWithDateArray[indexPath.section];
        NSArray *dataArray = dicSection[@"data"];
        NSDictionary *dic = dataArray[indexPath.row];
//        NSNumber *isSure = dic[@"isSure"];
//        if (isSure.integerValue==0) {
            [self performSegueWithIdentifier:@"toDetail" sender:dic[@"id"]];
//        }
    }
}

-(IBAction)importanceAction{
    if (self.tableView.indexPathsForSelectedRows.count!=0) {
        NSMutableString *idsString = [[NSMutableString alloc]init];
        for (NSIndexPath *indexPath in self.tableView.indexPathsForSelectedRows) {
            NSDictionary *dic = self.dataWithDateArray[indexPath.section][@"data"][indexPath.row];
            [idsString appendFormat:@"%@,",dic[@"id"]];
        }
        NSString *string = [idsString substringToIndex:idsString.length-1];
        NSLog(@"%@",string);
        NSString *urlString = [NSString stringWithFormat:@"%@/message/importance.do?state=1&ids=%@",JSXF_HOST,string];
        
        [SVProgressHUD show];
        
        [ZCWebServiceHelper requestWithMethod:GET andUrlStr:urlString andParameters:nil andFinished:^(id response, NSURLSessionDataTask *dataTask) {
            //            [SVProgressHUD dismiss];
            [self sendRequestForLoadData];
        }];
    }
}

-(IBAction)lockAction{
    if (self.tableView.indexPathsForSelectedRows.count!=0) {
        NSMutableString *idsString = [[NSMutableString alloc]init];
        for (NSIndexPath *indexPath in self.tableView.indexPathsForSelectedRows) {
            NSDictionary *dic = self.dataWithDateArray[indexPath.section][@"data"][indexPath.row];
            [idsString appendFormat:@"%@,",dic[@"id"]];
        }
        NSString *string = [idsString substringToIndex:idsString.length-1];
        NSLog(@"%@",string);
        NSString *urlString = [NSString stringWithFormat:@"%@/message/lock.do?state=1&ids=%@",JSXF_HOST,string];
        
        [SVProgressHUD show];
        
        [ZCWebServiceHelper requestWithMethod:GET andUrlStr:urlString andParameters:nil andFinished:^(id response, NSURLSessionDataTask *dataTask) {
            //            [SVProgressHUD dismiss];
            [self sendRequestForLoadData];
        }];
    }
}

-(IBAction)deleteAction{
    if (self.tableView.indexPathsForSelectedRows.count!=0) {
        NSMutableString *idsString = [[NSMutableString alloc]init];
        for (NSIndexPath *indexPath in self.tableView.indexPathsForSelectedRows) {
            NSDictionary *dic = self.dataWithDateArray[indexPath.section][@"data"][indexPath.row];
            if (((NSNumber*)dic[@"isLock"]).integerValue==0) {
                [idsString appendFormat:@"%@,",dic[@"id"]];
            }
        }
        NSString *string = [idsString substringToIndex:idsString.length-1];
        NSLog(@"%@",string);
        NSString *urlString = [NSString stringWithFormat:@"%@/message/delete.do?ids=%@",JSXF_HOST,string];
        
        [SVProgressHUD show];
        
        [ZCWebServiceHelper requestWithMethod:GET andUrlStr:urlString andParameters:nil andFinished:^(id response, NSURLSessionDataTask *dataTask) {
            //            [SVProgressHUD dismiss];
            [self sendRequestForLoadData];
        }];
    }
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"toDetail"]) {
        DQRSXDetailTableViewController *vc = segue.destinationViewController;
        vc.dataId = sender;
    }
}


@end
